#pragma
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <functional>
#include <cstring>
#include"Mutex.hpp"
#include "Log.hpp"
using namespace MuteModule;
using namespace LogModule;
using func_t = std::function<std::string(const std::string&)>;

class Server
{
public:
    Server(/*const std::string ip,*/ uint16_t port, func_t f)
    :_port(port),
     //_ip(ip),
     _socketfd(-1),
     _f(f)
    {
        
    }
    //初始化服务器
    void Init()
    {
        //首先要初始化服务器
        _socketfd = socket(AF_INET,SOCK_DGRAM,0);//成功返回一个文件描述符,失败返回-1
        if(_socketfd < 0)
        {
            LOG(LogLevel::DEBUG) << "sockert error";
            exit(1);
        }
        LOG(LogLevel::DEBUG) << "sockert success: " << _socketfd;


        struct sockaddr_in server;
        bzero(&server,sizeof server);//将结构体清空
        server.sin_family = AF_INET;//协议簇
        server.sin_port = htons(_port);//端口号
        //server.sin_addr.s_addr = inet_addr(_ip.c_str());//ip地址
        server.sin_addr.s_addr = INADDR_ANY;
         
        //与服务器建立连接
        int n = bind(_socketfd, (struct sockaddr *)&server, sizeof server);//成功返回0,失败返回-1
        if(n < 0)
        {
            LOG(LogLevel::DEBUG) << "bind error";
            exit(1);
        }
        LOG(LogLevel::DEBUG) << "bind success: " << _socketfd;
    }
    //启动服务器
    void Start()
    {
        while(true)
        {
            //读取客户端写入的数据
            char buffer[1024];
            struct sockaddr_in server;
            unsigned int len = sizeof(server);
            int n = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&server, &len);//记录下来谁发给我的
            uint16_t port = ntohs(server.sin_port);
            std::string ip = inet_ntoa(server.sin_addr);
            if(n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::DEBUG) << "[IP : " << ip <<"]" << "[port : " << port << "]" << "client say# " << buffer;
                std::string say = _f(buffer);
                // say += "server@ ";
                // say += buffer; 
                //向客户端发送数据
                int t = sendto(_socketfd, say.c_str(), say.size(), 0, (struct sockaddr *)&server, len);//我发给谁
            }
            
        }
    }
    ~Server()
    {

    }
private:
    int _socketfd;
    uint16_t _port;
    std::string _ip;

    func_t _f;
};